﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace 客户端
{
    public partial class Form1 : Form
    {
        private Thread th1 = null;//创建线程
         Socket socketSend = null;
        public Form1()
        {
            InitializeComponent();
            //关闭 跨线程检测
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            /*******客户端*******/
            try
            {
                //创建一个负责监IP地址跟端口号的Socket
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


                //创建IP端口和对象
                IPAddress ip = IPAddress.Parse(txt_IP.Text.Trim());
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txt_point.Text.Trim()));

                socketSend.Connect(point);
                txt_msg.AppendText("连接成功\r\n");

                //开启一个线程 不停的接受服务端发来的消息
                th1 = new Thread(Recive);//传入方法
                th1.IsBackground = true; //线程设置副线程
                                         //线程开始等待
                th1.Start();//执行Listen方法 等待客户端的链接，并创建与之通讯用的Socket
            }
            catch (Exception err)
            {
                txt_msg.AppendText( "连不上服务器 \r\n");
                socketSend.Close();
                //throw;
            }
            

        }


        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            string str_msg = txt_send.Text.Trim();//发送的消息
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str_msg);//转字节数

            socketSend.Send(buffer);//向服务器发送字节
            txt_receive.AppendText("我 [" + DateTime.Now.ToLongTimeString()+"] : "+str_msg + "\r\n");
            txt_send.Text = "";
        }

        /// <summary>
        /// 客户端不停的接受服务器端发过来的消息
        /// </summary>
        /// <param name="o"></param>
        void Recive()
        {
            while (true)
            {
                try
                {
                    //客户端链接成功后，服务器应该接受客户端发来的消息
                    byte[] buffer = new byte[1024 * 1024 * 2];//字节数
                    int r = socketSend.Receive(buffer);//实际接受到的有效字节数量

                    if (r == 0)//判断如果是空消息就退出循环
                    {
                        txt_msg.AppendText(socketSend.RemoteEndPoint.ToString() + " : 退出链接 \r\n");
                        break;
                    }

                    string str_msg = Encoding.UTF8.GetString(buffer, 0, r);//把接受到的字节转成字符串

                    //显示消息
                    txt_receive.AppendText(socketSend.RemoteEndPoint.ToString() + " [" + DateTime.Now.ToLongTimeString() + "] : " + str_msg + "\r\n");

                }
                catch (Exception e)
                {

                    txt_msg.AppendText("服务器出错\r\n");
                    socketSend.Close();
                   
                    break;
                 //  throw;
                }


            }
        }


        private void Form1_Load(object sender, EventArgs e)
        {

        }

        //自动发送
        private void button3_Click(object sender, EventArgs e)
        {
            Thread th3 = new Thread(()=> {
                while (true)
                {
                    string str_msg = textBox1.Text.Trim();//发送的消息
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str_msg);//转字节数

                    socketSend.Send(buffer);//向服务器发送字节
                    txt_receive.AppendText("我 [" + DateTime.Now.ToLongTimeString() + "] : " + str_msg + "\r\n");

                    Thread.Sleep(10000);
                }
            });
            th3.Start();
            th3.IsBackground = true;

        }

        private void button4_Click(object sender, EventArgs e)
        {
        

            Thread th4 = new Thread(() =>
            {
                while (true)
                {
                    Random rd = new Random();
                    double i = rd.Next(9999);
                    string str_msg = "##ST=32;CN=2011;PW=123456;MN=12200G0B00000F0SO0H0M00H;CP=&&DateTime=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";g13301-Rtd="+ (i / 100).ToString() + ",g13301-Flag=D;g12501-Rtd=-03.992,g12501-Flag=N;g20801-Rtd=000.000,g20801-Flag=D&&";//发送的消息
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str_msg);//转字节数

                    socketSend.Send(buffer);//向服务器发送字节
                    txt_receive.AppendText("我 [" + DateTime.Now.ToLongTimeString() + "] : " + str_msg + "\r\n");

                    Thread.Sleep(10000);
                }
            });
            th4.Start();
            th4.IsBackground = true;
        }
    }
}
